package cn.virens.util.poi;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;

import cn.virens.util.poi.exception.ReadExcelException;

public class ReadUtil {
	public static String getString(Cell cell) throws ReadExcelException {
		if (cell == null) return null;
		CellType type = cell.getCellTypeEnum();
		if (CellType.ERROR.equals(type)) {
			return "";
		} else if (CellType.NUMERIC.equals(type) && DateUtil.isCellDateFormatted(cell)) {
			return DateFormatUtils.format(cell.getDateCellValue(), "yyyy-MM-dd HH:mm:ss");
		} else if (CellType.NUMERIC.equals(type)) {
			return Double.toString(cell.getNumericCellValue());
		} else {
			return cell.toString();
		}
	}

	public static Integer getInteger(Cell cell) throws ReadExcelException {
		String value = getString(cell);
		try {
			if (StringUtils.isEmpty(value)) {
				return null;
			} else {
				return Integer.parseInt(value);
			}
		} catch (Exception e) {
			throw new ReadExcelException(value, cell, "非有效的数字", e);
		}
	}

	public static Float getFloat(Cell cell) throws ReadExcelException {
		String value = getString(cell);

		try {
			if (StringUtils.isEmpty(value)) {
				return null;
			} else {
				return Float.parseFloat(value);
			}
		} catch (Exception e) {
			throw new ReadExcelException(value, cell, "非有效的数字", e);
		}
	}

	public static Boolean getBoolean(Cell cell) throws ReadExcelException {
		String value = getString(cell);

		if (StringUtils.isEmpty(value)) {
			return null;
		} else {
			return StringUtils.equalsAnyIgnoreCase(value, "true", "on", "1", "是");
		}
	}

	public static Date getDate(Cell cell) throws ReadExcelException {
		if (cell == null) return null;

		CellType type = cell.getCellTypeEnum();
		if (CellType.BLANK.equals(type) || CellType.ERROR.equals(type)) {
			return null;
		} else if (CellType.NUMERIC.equals(type)) {
			if (DateUtil.isCellDateFormatted(cell)) {
				return cell.getDateCellValue();
			} else {
				return format(cell.toString());
			}
		} else {
			return format(cell.toString());
		}
	}

	protected static Date format(String string) {
		try {
			string = StringUtils.trim(string);
			string = StringUtils.removeAll(string, "[\\t\\n\\r]");
			string = StringUtils.replaceAll(string, "[/|年|月|日|.]", "-");
			string = StringUtils.removeEnd(string, "-");

			return DateUtils.parseDate(string, "yyyy", "yyyy-MM", "yyyy-MM-dd");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}
